package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.Classes;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.R;
import com.bnz.pojo.Student;
import com.bnz.service.ClassesService;
import com.bnz.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {
    @Autowired
    private ClassesService classesService;
    @Override
    public void init() throws ServletException {
        //在servlet中拿到spring容器。
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //得到studentService
        classesService = webApplicationContext.getBean(ClassesService.class);

    }
    //班级信息
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
       List<Classes> classes =  classesService.findAll();
       //将学生对象转化为json对象。
        R data = R.ok().data("data", classes);
        resp.getWriter().println(JSON.toJSONString(data));
        //刷新页面
        resp.getWriter().flush();
    }
}
